package com.chapter6;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ServletConfigTest extends HttpServlet {
    private ServletConfig config;

    public ServletConfigTest() {
        super();
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);//获取web.xml配置信息到config
        this.config = config;//将配置信息赋值给私有属性config
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws SecurityException, IOException {
        String charset = this.config.getInitParameter("charset");
        response.setCharacterEncoding(charset);
        response.setContentType("text/html");//设置响应正文的MIME类型
        PrintWriter out = response.getWriter();
        //返回一个PrintWrite对象，Servlet使用它来输出字符串形式的正文数据
        //以下为输出的HTML正文数据
        out.println("<HTML>");
        out.println("<HEAD><TITLE>ServletConfigTest</TITLE></HEAD>");
        out.println("<BODY>");
        out.println("获取lnitParamServlet的初始化参数\"charset\"的字符串值:" + charset);
        out.println("</BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws SecurityException, IOException {
        doPost(request, response);
    }
}
